using Microsoft.EntityFrameworkCore;
using MinimalistFoodStreet.BackEnd.Infrastructure.Attributes;
using MinimalistFoodStreet.BackEnd.Infrastructure.Dtos.Request.Tables;
using MinimalistFoodStreet.BackEnd.Infrastructure.Dtos.Response;
using MinimalistFoodStreet.BackEnd.Infrastructure.Dtos.Response.Tables;
using MinimalistFoodStreet.BackEnd.Infrastructure.EFCore;
using MinimalistFoodStreet.BackEnd.Server.Server.RequestExtend.Tables;
using MinimalistFoodStreet.BackEnd.Server.Server.ResponseExtend.Tables;
using MinimalistFoodStreet.BackEnd.Server.IServer.Tables;

namespace MinimalistFoodStreet.BackEnd.Server.Server.Tables
{
    [InjectClass]
    public class InfosServer : IInfosServer
    {
        private readonly ServerRepository _serverRepository;
        public InfosServer(DbContext dbContext)
        {
            _serverRepository = new ServerRepository(dbContext);
        }

        public async Task<ResponseApiDto> AddAsync(RequestCreateInfosDto dto)
        {
            int affectedRows = await _serverRepository.infosEFCore.AddAsync(dto.ToCreateEntity());
            return ResponseApiDto.Create(affectedRows);
        }

        public async Task<ResponseApiDto> UpdateAsync(RequestUpdateInfosDto dto)
        {
            Info info = await _serverRepository.infosEFCore.Query(d => d.IId == dto.id).SingleOrDefaultAsync();
            if (info == null)
            {
                return ResponseApiDto.Fail("该实例不存在");
            }
            int affectedRows = await _serverRepository.infosEFCore.UpdateAsync(info);
            return ResponseApiDto.Create(affectedRows);
        }

        public async Task<ResponseApiDto> DeleteAsync(RequestDeleteInfosDto dto)
        {
            int affectedRows = await _serverRepository.infosEFCore.Query(d => d.IId == dto.id).ExecuteDeleteAsync();
            if (affectedRows == 0)
            {
                return ResponseApiDto.Fail("该实例不存在");
            }
            return ResponseApiDto.Create(affectedRows);
        }

        public async Task<ResponseApiDto> DetailAsync(int id)
        {
            Info info = await _serverRepository.infosEFCore.Query(d => d.IId == id).SingleOrDefaultAsync();
            if (info == null)
            {
                return ResponseApiDto.Fail("该实例不存在");
            }
            return ResponseApiDto.Ok("数据已获取", info.ToResponseDto());
        }

        public async Task<ResponseApiDto> PaginationAsync(int page, int limit, string? key)
        {
            int total = 0;
            List<Info> infos = await _serverRepository.infosEFCore.Pagination(d => true, false, d => d.IId, out total, page, limit).ToListAsync();
            List<ResponseInfosDto> responseInfosDtos = infos.Select(d => d.ToResponseDto()).ToList();
            return ResponseApiDto.Ok("数据已获取", new { data = responseInfosDtos, total = total });
        }
    }
}